<template>
  <view class="container">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-state">
      <up-icon name="loading" size="60" color="#1890ff"></up-icon>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 错误状态 -->
    <view v-if="error && !loading" class="error-state">
      <up-icon name="error-circle" size="60" color="#f56c6c"></up-icon>
      <text class="error-text">{{ errorMessage }}</text>
      <button class="retry-btn" @click="reloadPage">重试</button>
    </view>

    <!-- 正常内容 -->
    <view v-if="!loading && !error">
      <!-- 商品图片轮播 -->
      <view class="goods-swiper">
        <swiper
            class="goods-swiper__container"
            :indicator-dots="true"
            :autoplay="true"
            interval="5000"
            duration="500"
        >
          <swiper-item
              v-for="(img, index) in itemDetail.images"
              :key="index"
              class="goods-swiper__item"
          >
            <image :src="img" mode="aspectFill" class="goods-swiper__image"></image>
          </swiper-item>
        </swiper>
      </view>

      <!-- 商品信息 -->
      <view class="goods-info">
        <view class="goods-info__price-container">
          <view class="goods-info__price-current">¥{{ itemDetail.price }}</view>
          <view class="goods-info__price-original" v-if="itemDetail.originalPrice">¥{{ itemDetail.originalPrice }}</view>
          <view class="goods-info__price-discount" v-if="itemDetail.originalPrice">
            {{ Math.round((1 - itemDetail.price / itemDetail.originalPrice) * 10) }}折
          </view>
        </view>

        <view class="goods-info__title">{{ itemDetail.title }}</view>

        <view class="goods-info__tags">
          <view class="goods-info__tag" v-for="(tag, index) in itemDetail.tags" :key="index">
            {{ tag }}
          </view>
        </view>

        <view class="divider"></view>

        <view class="goods-info__description">
          <view class="goods-info__description-title">商品描述</view>
          <view class="goods-info__description-content">{{ itemDetail.description }}</view>
        </view>

        <view class="divider"></view>

        <view class="goods-info__meta">
          <view class="goods-info__meta-item">
            <text class="goods-info__meta-label">发布时间：</text>
            <text class="goods-info__meta-value">{{ formatTime(itemDetail.createTime) }}</text>
          </view>
          <view class="goods-info__meta-item">
            <text class="goods-info__meta-label">浏览量：</text>
            <text class="goods-info__meta-value">{{ itemDetail.viewCount || 0 }}</text>
          </view>
        </view>
      </view>

      <!-- 卖家信息 -->
      <view class="seller-info" :style="{ marginBottom: bottomBarHeight ? `${bottomBarHeight + 20}px` : '80px' }">
        <view class="seller-info__header" @click="goSeller">
          <image
              :src="itemDetail.avatar"
              class="seller-info__avatar"
          ></image>
          <view class="seller-info__name-info">
            <text class="seller-info__name">{{ itemDetail.nickName || '匿名卖家' }}</text>
            <text class="seller-info__status" :class="{ 'seller-info__status--verified': itemDetail.isAuth }">
              {{ itemDetail.isAuth ? '已认证' : '未认证' }}
            </text>
          </view>
          <view class="seller-info__stats">
            <view class="seller-info__stat-item">
              <text class="seller-info__stat-value">{{ itemDetail.soldCount || 10 }}</text>
              <text class="seller-info__stat-label">已售出</text>
            </view>
            <view class="seller-info__stat-item">
              <text class="seller-info__stat-value">{{ itemDetail.onSaleCount || 2 }}</text>
              <text class="seller-info__stat-label">在售</text>
            </view>
          </view>
        </view>
        <view class="seller-info__contact-btn" @click="contactSeller" v-if="!isOwnProduct">
          <up-icon name="chat" size="18"></up-icon>
          <text>联系卖家</text>
        </view>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar" :class="{ 'bottom-bar--hidden': !isBottomBarVisible }">
      <!-- 购物车按钮（仅非自己发布的商品显示） -->
      <view class="bottom-bar__cart" @click="addToCart" v-if="!isOwnProduct">
        <up-icon name="shopping-cart" size="24"></up-icon>
        <view class="bottom-bar__cart-count" v-if="cartCount > 0">{{ cartCount }}</view>
      </view>

      <view class="bottom-bar__actions">
        <!-- 非自己发布的商品显示"立即购买" -->
        <view class="bottom-bar__buy" @click="buyItem" v-if="!isOwnProduct">
          <text>立即购买</text>
        </view>

        <!-- 自己发布的商品显示"管理" -->
        <view class="bottom-bar__manage" @click="goToManage" v-if="isOwnProduct">
          <text>管理商品</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import {ref, onMounted, getCurrentInstance, nextTick, computed} from 'vue';
import {request} from '@/utils/request';
import {selectDetail} from "@/apis/shopAPI";

const {proxy} = getCurrentInstance();

// 状态管理
const itemDetail = ref({
  images: [],
  sellerId: '',  // 商品发布者ID
  currentUserId: ''  // 当前登录用户ID
});

const loading = ref(true);
const error = ref(false);
const errorMessage = ref('获取商品信息失败');
const userInfo = uni.getStorageSync('userInfo');

// 购物车状态
const cartCount = ref(0);
const isAddingToCart = ref(false);

// 底部栏控制
const bottomBarHeight = ref(0);
const isBottomBarVisible = ref(true);
const lastScrollTop = ref(0);

// 判断是否为自己发布的商品
const isOwnProduct = computed(() => {
  // 确保用户已登录且商品信息已加载
  return itemDetail.value.currentUserId && itemDetail.value.sellerId
      && itemDetail.value.currentUserId === itemDetail.value.sellerId;
});

// 初始化
onMounted(() => {
  initPage();
  calculateBottomBarHeight();

  // 添加滚动事件监听
  window.addEventListener('scroll', handleScroll);

  // 页面卸载时移除监听
  return () => {
    window.removeEventListener('scroll', handleScroll);
  };
});

// 计算底部栏高度
const calculateBottomBarHeight = () => {
  nextTick(() => {
    const bottomBar = document.querySelector('.bottom-bar');
    if (bottomBar) {
      bottomBarHeight.value = bottomBar.offsetHeight;
    }
  });
};

//点击头像跳转到商家个人信息页面
const goSeller = () => {
  uni.navigateTo({
    url: `/pages/shop/shop-detail?id=${itemDetail.value.sellerId}`
  })
}

// 处理滚动事件
const handleScroll = () => {
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
  // 判断用户是向上滚动还是向下滚动
  if (scrollTop > lastScrollTop.value && scrollTop > 100) {
    // 向下滚动且超过一定距离，隐藏底部栏
    isBottomBarVisible.value = false;
  } else {
    // 向上滚动，显示底部栏
    isBottomBarVisible.value = true;
  }
  lastScrollTop.value = scrollTop;
};

// 页面初始化
const initPage = () => {
  const eventChannel = proxy.getOpenerEventChannel();
  eventChannel.on('acceptDataFromOpenerPage', async (data) => {
    try {
      loading.value = true;
      error.value = false;
      if (data.itemData?.id) {
        handleItemData(data.itemData);
        console.log('itemDetail', data.itemData);
      } else if (data.itemId) {
        const itemData = await fetchItemDetailFromApi(data.itemId);
        handleItemData(itemData);
      } else {
        throw new Error('缺少商品ID');
      }
    } catch (err) {
      console.error('初始化页面失败:', err);
      error.value = true;
      errorMessage.value = err.message || '获取商品信息失败';
    } finally {
      loading.value = false;
    }
  });
};

// 处理商品数据
const handleItemData = (data) => {
  console.log('原始商品数据:', data);

  // 打印关键ID信息用于调试
  console.log('接口返回的userId:', data.userId);
  console.log('接口返回的sellerId:', data.sellerId);
  console.log('当前登录用户ID:', userInfo.userId);

  // 处理图片数组，添加错误处理
  let images = [];
  if (data.images && Array.isArray(data.images)) {
    images = data.images;
  } else if (data.file) {
    try {
      // 尝试解析JSON
      images = JSON.parse(data.file);
      if (!Array.isArray(images)) {
        images = [data.file]; // 如果解析后不是数组，使用原始值作为唯一元素
      }
    } catch (e) {
      console.error('解析图片数据失败:', e);
      images = [data.file]; // 解析失败，使用原始值作为唯一元素
    }
  }

  // 确保价格是正确的数字格式
  const price = parseFloat(data.price || 0);
  const originalPrice = parseFloat(data.originalPrice || 0);

  itemDetail.value = {
    ...data,
    id: data.id || '',
    // 明确区分：currentUserId为当前登录用户ID，sellerId为商品发布者ID
    currentUserId: userInfo.userId || '',
    sellerId: data.sellerId || data.userId || '', // 优先使用sellerId，其次使用userId
    title: data.title || '商品名称',
    price: price.toFixed(2),
    originalPrice: originalPrice > 0 ? originalPrice.toFixed(2) : '',
    description: data.description || '暂无商品描述',
    createTime: data.createTime || '',
    images,
    tags: data.tags || (data.type_id === 1 ? ['闲置出售'] : ['求购宝贝']),
    nickName: data.nickName || '',
    avatar: data.avatar || '',
    isAuth: data.isAuth || false,
    soldCount: data.soldCount || 0,
    onSaleCount: data.onSaleCount || 0,
    viewCount: data.viewCount || 0,
    comments: data.comments || []
  };

  console.log('处理后的商品数据:', itemDetail.value);
  console.log('是否为自己发布的商品:', isOwnProduct.value);
};

// 接口调用
const fetchItemDetailFromApi = async (itemId) => {
  try {
    const res = await selectDetail(itemId);
    if (res.data.code === 200) {
      return res.data.data;
    }
    throw new Error(res.data.message || '获取商品详情失败');
  } catch (err) {
    console.error('获取商品详情失败:', err);
    throw err;
  }
};

// 添加到购物车
const addToCart = async () => {
  if (isAddingToCart.value) return;
  try {
    isAddingToCart.value = true;
    const res = await request({
      url: '/api/cart/add',
      method: 'POST',
      data: {
        productId: itemDetail.value.id,
        quantity: 1
      }
    });
    if (res.statusCode === 200 && res.data.code === 200) {
      cartCount.value += 1;
      uni.showToast({title: '已添加到购物车', icon: 'success', duration: 1500});
      setTimeout(() => {
        isAddingToCart.value = false;
      }, 500);
    } else {
      uni.showToast({title: res.data.message || '添加失败', icon: 'none'});
      isAddingToCart.value = false;
    }
  } catch (err) {
    console.error('添加购物车失败:', err);
    uni.showToast({title: '网络错误，请重试', icon: 'none'});
    isAddingToCart.value = false;
  }
};

// 工具方法
const formatTime = (time) => {
  if (!time) return '';
  const date = new Date(time);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
};

// 页面交互
const goBack = () => uni.navigateBack();

// 点击联系卖家
const contactSeller = () => {
  uni.navigateTo({
    url: `/pages/message/chat?userId=${itemDetail.value.sellerId}` // 使用sellerId
  });
};

// 点击购买
const buyItem = () => {
  const itemData = {
    id: itemDetail.value.id,
    title: itemDetail.value.title,
    price: itemDetail.value.price,
    sellerId: itemDetail.value.sellerId, // 使用sellerId
    createTime: itemDetail.value.createTime,
    images: itemDetail.value.images // 添加图片信息
  };
  console.log('传递到确认订单页的商品数据:', itemData);
  uni.navigateTo({
    url: '/pages/shop/play-confirm',
    success: (res) => {
      res.eventChannel.emit('acceptProductData', {productInfo: itemData});
    }
  });
};

// 跳转到商品管理页
const goToManage = () => {
  if (!itemDetail.value.id) {
    uni.showToast({title: '商品信息错误', icon: 'none'});
    return;
  }
  // 跳转到商品编辑/管理页面
  uni.navigateTo({
    url: `/pages/shop/manage-goods?id=${itemDetail.value.id}`
  });
};

// 加入购物车
const navigateToCart = () => {
  uni.navigateTo({url: '/pages/shop/shop-car'});
};

const shareItem = () => {
  uni.showShareMenu({
    withShareTicket: true,
    menus: ['shareAppMessage', 'shareTimeline']
  });
};

// 重新加载页面
const reloadPage = () => {
  error.value = false;
  initPage();
};
</script>

<style scoped>
/* 基础样式 */
.container {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  font-size: 14px;
  color: #333;
}

/* 加载状态 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
}

.loading-text {
  margin-top: 12px;
  font-size: 14px;
  color: #999;
}

/* 错误状态 */
.error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
}

.error-text {
  margin: 16px 0 24px;
  font-size: 16px;
  color: #f56c6c;
}

.retry-btn {
  background-color: #1890ff;
  color: #fff;
  border: none;
  padding: 8px 24px;
  border-radius: 4px;
  font-size: 14px;
}

/* 顶部导航栏 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 48px;
  padding: 0 16px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 10;
}

.header__back-btn,
.header__share-btn {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.header__title {
  font-size: 18px;
  font-weight: 500;
}

/* 商品图片轮播 */
.goods-swiper {
  width: 100%;
  height: 400px;
}

.goods-swiper__container {
  width: 100%;
  height: 100%;
}

.goods-swiper__image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 商品信息 */
.goods-info {
  background-color: #fff;
  padding: 16px;
  margin-bottom: 12px;
}

.goods-info__price-container {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.goods-info__price-current {
  font-size: 24px;
  color: #ff4d4f;
  font-weight: bold;
}

.goods-info__price-original {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
  margin-left: 8px;
}

.goods-info__price-discount {
  font-size: 12px;
  color: #fff;
  background-color: #ff4d4f;
  padding: 2px 4px;
  border-radius: 4px;
  margin-left: 8px;
}

.goods-info__title {
  font-size: 18px;
  line-height: 1.5;
  margin-bottom: 12px;
  color: #333;
  font-weight: 500;
}

.goods-info__tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 16px;
}

.goods-info__tag {
  font-size: 12px;
  padding: 4px 8px;
  background-color: #f5f5f5;
  color: #666;
  border-radius: 4px;
}

.divider {
  height: 1px;
  background-color: #f5f5f5;
  margin: 16px 0;
}

.goods-info__description {
  margin-bottom: 8px;
}

.goods-info__description-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
  color: #333;
}

.goods-info__description-content {
  font-size: 14px;
  line-height: 1.6;
  color: #666;
  white-space: pre-line;
}

.goods-info__meta {
  padding: 8px 0;
}

.goods-info__meta-item {
  display: flex;
  margin-bottom: 8px;
}

.goods-info__meta-label {
  color: #999;
  flex-shrink: 0;
}

.goods-info__meta-value {
  color: #666;
  flex: 1;
}

/* 卖家信息 */
.seller-info {
  background-color: #fff;
  padding: 16px;
}

.seller-info__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.seller-info__avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
}

.seller-info__name-info {
  flex: 1;
  margin-left: 12px;
}

.seller-info__name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.seller-info__status {
  font-size: 12px;
  color: #999;
  margin-left: 8px;
}

.seller-info__status--verified {
  color: #1890ff;
}

.seller-info__stats {
  display: flex;
  justify-content: flex-end;
}

.seller-info__stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-left: 16px;
}

.seller-info__stat-value {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.seller-info__stat-label {
  font-size: 12px;
  color: #999;
}

.seller-info__contact-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 50px;
  height: 36px;
  border: 1px solid #1890ff;
  color: #1890ff;
  border-radius: 4px;
  font-size: 14px;
}

/* 底部操作栏 */
.bottom-bar {
  display: flex;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 56px;
  background-color: #fff;
  border-top: 1px solid #eee;
  z-index: 20;
  transition: transform 0.3s ease;
}

.bottom-bar.bottom-bar--hidden {
  transform: translateY(100%);
}

.bottom-bar__cart {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
}

.bottom-bar__cart-count {
  position: absolute;
  top: 4px;
  right: 12px;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background-color: #ff4d4f;
  color: #fff;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.bottom-bar__actions {
  flex: 4;
  display: flex;
}

.bottom-bar__add-cart,
.bottom-bar__buy,
.bottom-bar__manage {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  color: #fff;
}

.bottom-bar__add-cart {
  background-color: #fa8c16;
}

.bottom-bar__add-cart--loading {
  background-color: #d47a00;
}

.bottom-bar__buy {
  background-color: #ff4d4f;
}

.bottom-bar__manage {
  background-color: #1890ff; /* 管理按钮使用蓝色背景 */
}

/* 自己发布商品时隐藏购物车按钮的占位空间 */
.bottom-bar__cart:empty {
  display: none;
}
</style>